import paho.mqtt.client as mqtt

# 创建一个新的MQTT客户端实例
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

client.username_pw_set(username="123", password="123")
# 连接到MQTT服务器
client.connect('127.0.0.1')

# 定义回调函数
def on_connect(client, userdata, flags, reason_code, properties):
    if reason_code.is_failure:
        print(f"Failed to connect: {reason_code}. loop_forever() will retry connection")
    else:
        client.subscribe("mqtt/test")
        client.subscribe("mqtt/test*")

def on_message(client, userdata, msg):
    print(f"Received message '{msg.payload.decode()}' on topic '{msg.topic}' with QoS {msg.qos}")

# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 订阅主题
client.subscribe("test/topic")
client.subscribe("test/topic2")

# 发布一条消息
client.publish("test/topic", "Hello, MQTT!")

# 启动网络循环
client.loop_forever()